package cn.ecut.dao;

import cn.ecut.exception.DaoException;
import cn.ecut.model.User;
import cn.ecut.util.JDBCHelper;
import cn.ecut.util.TableNames;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao {
    public List<User> CheckLogin(User user){
        String Sql="select id,password,username from"+ TableNames.USER_TABLE_NAME+"where id=?";
        ResultSet resultSet= JDBCHelper.query(Sql,user.getId());
        List<User> users=warp(resultSet);
        return users;
    }

    public boolean SaveUser(User user){
        String sql="insert into"+TableNames.USER_TABLE_NAME+"(id,username,password,sex,tel) values (?,?,?,?,?)";
        return JDBCHelper.execute(sql,user.getId(),user.getUsername(),user.getPassword(),user.getSex(),user.getTel());
    }

    private List <User> warp(ResultSet resultSet) throws DaoException{
        List<User> list=new ArrayList<>();
        try {
            while(resultSet.next()){
                User u=new User();
                u.setId(resultSet.getString("id"));
                u.setPassword(resultSet.getString("password"));
                u.setUsername(resultSet.getString("username"));
                list.add(u);
            }
        } catch (SQLException e) {
            throw new DaoException("数据封装出错。");
        }
        return list;
    }

}
